<script setup>
import {onMounted, ref} from "vue";
import jsQR from "jsqr";
import {AppointmentService, DepartService} from "@/api/api";
const departmentsAllChild = ref([]);
const selectedDepartment = ref();
let scannedCode = '';
let patientName = '';
let message = ''
const showMessage = ref(false);
const isSuccess = ref(false);
// eslint-disable-next-line no-unused-vars
const ensure = async() => {
  showMessage.value = false;
  isSuccess.value = false;
  console.log(selectedDepartment.value.departmentId);
  const vars = document.getElementById("inputs");
  const callingMachineData = {
    number: vars.value,
    departmentId:selectedDepartment.value,
    // 其他字段根据需要添加
  };
  console.log(callingMachineData);
  // 调用后端API接口发送保存数据的请求
  const response = await AppointmentService.SignIn(callingMachineData);
  console.log(response);
  message = response.data.message;
  patientName = response.data.pname;
  scannedCode = response.data.appointmentNumber;
  showMessage.value = true;
  vars.value = "";
  if(message==='签到成功'){
    isSuccess.value = true;
  }
  // 10秒后隐藏签到信息
  setTimeout(() => {
    showMessage.value = false;
    isSuccess.value = false;

  }, 10000);
};

const scan = async(number) => {
  const vars = document.getElementById("inputs");
  vars.value = number;
  await ensure();
};

const startScan = async () => {
  try {
    const response1 = await DepartService.listHandle();
    departmentsAllChild.value = response1.data;
    const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });

    // 获取 video 元素的引用并设置其 srcObject 为获取到的媒体流
    document.getElementById("camera").srcObject = stream;
    document.getElementById("camera").play();

    const canvasElement = document.createElement('canvas');
    const canvas = canvasElement.getContext('2d');

    // 每隔一段时间读取视频流中的图像，并尝试识别
    const checkCode = () => {
      if (document.getElementById("camera").readyState === document.getElementById("camera").HAVE_ENOUGH_DATA) {
        canvasElement.height = document.getElementById("camera").videoHeight;
        canvasElement.width = document.getElementById("camera").videoWidth;
        canvas.drawImage(document.getElementById("camera"), 0, 0, canvasElement.width, canvasElement.height);
        const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
        const code = jsQR(imageData.data, imageData.width, imageData.height, {
          inversionAttempts: "dontInvert",
        });

        if (code) {
          console.log("找到二维码", code.data);
          // 停止摄像头
          stream.getTracks().forEach(track => track.stop());
          // 存储二维码数据
          scan(code.data);
          setTimeout(() => {
            startScan();
          }, 500);
        } else {
          // 继续检查
          requestAnimationFrame(checkCode);
        }
      } else {
        requestAnimationFrame(checkCode);
      }
    };

    checkCode();
  } catch (e) {
    console.error(e);
  }
};



// eslint-disable-next-line no-unused-vars
const beforeUnmount = async () =>{
  // 停止摄像头并释放资源
  const camera = this.$refs.camera;
  if (camera && camera.srcObject) {
    camera.srcObject.getTracks().forEach(track => track.stop());
  }
};
const addStr = async (s) => {
  const vars = document.getElementById("inputs");
  vars.value = vars.value + s;
};

const del = async () => {
  const vars = document.getElementById("inputs");
  vars.value = vars.value.substr(0,vars.value.length-1);
};

const cls = async () => {
  const vars = document.getElementById("inputs");
  vars.value = "";
};

onMounted(() => {
  document.body.style.backgroundImage = "url('https://img.ixintu.com/download/jpg/202002/bb6891d3b60d4835aad9416cac34bb59.jpg%21con')";
  document.body.style.backgroundSize = "cover";
  document.body.style.backgroundRepeat = "no-repeat";
  document.body.style.backgroundPosition = "center center";
  startScan();
});
</script>

<template>
  <div class="head">
    <h1 style="font-size: 60px; color: yellow;">门诊报到机</h1>
  </div>
  <div class="root">
    <div class="left">
      <div>
        <p style="font-size: 30px; color: yellow;">请输入身份证号或者登记号</p>
        <input id="inputs" type="text" disabled="disabled" ><button @click="ensure()"   >确认</button>
      </div>
      <div id="forcat" >
        <button @click="addStr(1)"   >1</button>
        <button @click="addStr(2)"  >2</button>
        <button @click="addStr(3)"  >3</button>
        <button @click="del()" >回删</button>
        <button @click="cls()"  >清空</button><br>
        <button @click="addStr(4)"  >4</button>
        <button @click="addStr(5)"  >5</button>
        <button @click="addStr(6)"  >6</button>
        <button @click="addStr('X')"  >X</button>
        <button @click="addStr('*')">*</button><br>
        <button @click="addStr(7)"  >7</button>
        <button @click="addStr(8)"  >8</button>
        <button @click="addStr(9)"  >9</button>
        <button @click="addStr(0)"  >0</button>
        <button @click="addStr('#')"  >#</button>
      </div>
      <div v-if="showMessage"  id="message">
        <p style="font-size: 30px; color: yellow;">{{message}}</p>
        <p v-if="isSuccess" style="font-size: 30px; color: yellow;">姓名：{{patientName}}</p>
        <p v-if="isSuccess" style="font-size: 30px; color: yellow;">号码： {{ scannedCode }}</p>
      </div>
    </div>
    <div class="center">
      <div>
        <div style="display: flex; justify-content: center; align-items: center; flex-direction:column;">
          <p style="font-size: 30px; color: yellow;">扫码签到</p>
          <video id="camera" width="300" height="300"></video>
        </div>
      </div>
    </div>

    <div class="right">
      <div class="tcRight">
        <label for="fruit">选择科室</label>
        <select id="fruit" v-model="selectedDepartment" required>
          <option disabled value="">请选择</option>
          <option v-for="department in departmentsAllChild" :key="department.departId" :value="department.departId">{{ department.dname }}</option>
        </select>
      </div>
      <p>温馨提示：<br>1.报到前确保已挂号且为今日就诊；<br>
        2.微信挂号的患者请一次点开”查看——就诊记录——切换实际就诊人——挂号医生“，调出条码，在条码扫描区报到；<br>
      </p>
    </div>
  </div>


</template>

<style scoped>

.root {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 定义两列，每列占用可用空间的一半 */
  height: 100vh; /* 设置为视口高度 */
}

.left, .right ,.center{
  flex-direction: column;
}

#inputs {
  width: 250px; /* 输入框宽度占满父元素宽度 */
  height: 50px; /* 输入框高度 */
  font-size: 20px; /* 输入框内文字大小 */
  margin-bottom: 10px; /* 与下方元素的间隔 */
}

/* 设置按钮的基础样式 */
button {
  width: 60px; /* 按钮宽度 */
  height: 60px; /* 按钮高度 */
  font-size: 20px; /* 按钮内文字大小 */
  margin: 5px; /* 按钮之间的间隔 */
}
video {
  display: block;
  visibility: visible;
}
.head{
  width: 100%; /* 确认按钮宽度占满父元素宽度 */
  height: 80px;
}
/* 特定按钮的样式调整，比如确认按钮 */
button[onclick="ensure"] {
  width: 60px; /* 确认按钮宽度占满父元素宽度 */
  height: 50px; /* 确认按钮高度 */
  font-size: 20px; /* 确认按钮内文字大小 */
  margin-top: 10px; /* 与上方元素的间隔 */
}
</style>
